<template>
  <div class="dataTable">
    <div class="header">
      <div class="flex">
        <div class="key_icon" />
        <div>系统配置</div>
      </div>
    </div>
    <div class="dashboard">
      <el-form ref="configForm" label-width="100px" :inline="false" :model="configForm">

        <el-form-item label="系统操作：">
          <el-button
            class="clearLinuxButton"
            :loading="loading"
            plain
            @click="handleEmptyLinux"
          >清空虚拟机</el-button>
          <p class="clearLinuxTip">清空虚拟机将会强制关闭所有空闲/使用中的虚拟机，请谨慎操作！</p>
        </el-form-item>

        <el-divider />

        <el-form-item label="开启虚拟机：">
          <el-radio-group v-model="configForm.config_type" class="radioGroup" @change="onLinuxChange">
            <div class="radioGroupItem">
              <el-radio :label="1">是</el-radio>
            </div>
            <div class="radioGroupItem">
              <el-radio :label="0">否</el-radio>
            </div>

            <div class="radioGroupItem">
              <el-radio :label="2">指定时间开启</el-radio>
            </div>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="" prop="config_value">
          <el-date-picker
            v-model="configForm.config_value"
            :disabled="isDatePickerClose"
            type="datetimerange"
            align="right"
            :picker-options="pickerOptions"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="timestamp"
          />
        </el-form-item>
        <el-button class="saveBtn" type="primary" :loading="loading" @click="onSave">保存</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
import { saveSystemSetup, getSystemSetup } from '@/api/config'

export default {
  name: 'DataTable',
  components: { },
  data() {
    return {
      isDatePickerClose: true,
      loading: true,
      configForm: {
        config_value: [],
        config_type: 0,
        config_name: 'open_docker_date'
      },
      // 时间控件配置
      pickerOptions: {
        // 当天以前的时间不可选
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 1 * 24 * 60 * 60 * 1000
        }
      }
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    // 清空虚拟机
    handleEmptyLinux() {
      this.$confirm('清空虚拟机将会强制关闭所有空闲/使用中的虚拟机，请谨慎操作！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await this.postCloseLinux()
      }).catch(() => { })
    },
    async postCloseLinux() {
      // closeall  POST
      this.loading = true

      const fetchUrl = process.env.VUE_APP_LINUX_URL === 'edu.docker.wenchu.cc' ? `https://${process.env.VUE_APP_LINUX_URL}/closeall` : `http://${process.env.VUE_APP_LINUX_URL}/closeall`
      fetch(fetchUrl,
        {
          method: 'post'
        })
        .then(response => response.json())
        .then(res => {
          this.loading = false
          const { data, code, message } = res
          if (code === 0) {
            // 清除缓存
            localStorage.removeItem('linuxData')
            this.$messageOnce.success('操作成功，已经关闭所有虚拟机！')
            return data
          } else {
            this.$messageOnce({
              message: `${message}`,
              type: 'error',
              duration: 2000
            })
          }
        })
        .catch(err => {
          this.$messageOnce({
            message: '关闭异常，请重试！',
            type: 'error',
            duration: 2000
          })
          this.loading = false
          console.log('Request Failed', err)
        })
    },
    async loadData() {
      this.loading = true
      try {
        const { code, data } = await getSystemSetup()
        if (code === 0) {
          this.initLoadData(data)
        }
        this.loading = false
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    initLoadData(data) {
      // 找到符合条件的数据
      const res = data.filter((item) => {
        return item.config_name === 'open_docker_date'
      })
      let configData = {}
      console.log(res)
      const { config_name, config_type, config_value } = res[0]
      if (config_type === 0) {
        // 选者关闭虚拟机
        configData = { config_type, config_value: [], config_name }
      } else if (config_type === 1 && config_value === '') {
        // 选者永远开启虚拟机
        configData = { config_type, config_value: [], config_name }
      } else if (config_type === 1 && config_value !== '') {
        // 选择指定时间开启
        const arrData = config_value.split('~')
        configData = { config_type: 2, config_value: arrData, config_name }
        this.isDatePickerClose = false
      } else {
        this.$messageOnce.error('初始化数据失败')
        return false
      }

      this.configForm = configData
    },
    onLinuxChange(data) {
      console.log(data)
      if (data === 2) {
        this.isDatePickerClose = false
      } else {
        this.isDatePickerClose = true
        this.configForm.config_value = []
      }
    },
    initPostData() {
      const { config_value, config_type, config_name } = this.configForm
      const config_value_length = config_value.length

      /**
   *        "config_name": "is_open_docker",
            "config_type": 2,
            "config_value": 1,//1开启0关闭
   */
      if (config_type === 0) {
        // 选者关闭虚拟机
        return { config_type, config_value: '', config_name }
      } else if (config_type === 1 && config_value_length === 0) {
        // 选者永远开启虚拟机
        return { config_type, config_value: '', config_name }
      } else if (config_type === 2 && config_value_length !== 0) {
        // 选择指定时间开启
        const timeStart = config_value[0]
        const timeEnd = config_value[1]
        return { config_type: 1, config_value: `${timeStart}~${timeEnd}`, config_name }
      } else {
        this.$messageOnce.error('初始化数据失败')
        return false
      }
    },
    onSave(data) {
      // console.log(data)
      this.$refs.configForm.validate(async(valid) => {
        if (valid) {
          this.loading = true
          try {
            console.log(this.configForm)

            // 处理数据
            const postData = this.initPostData()
            if (postData === false) throw new Error('初始化数据失败')

            // 请求接口
            const { code } = await saveSystemSetup(postData)
            if (!code) {
              this.$messageOnce.success('操作成功！')
            }
          } catch (error) {
            console.error(error)
          } finally {
            this.loading = false
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
p {
  margin: 0;
  padding: 0;
}
.dataTable {
	width: 1320px;
	min-height: 500px;
	background: #FFFFFF;
	box-shadow: 0px 6px 25px 0px rgba(0, 0, 0, 0.04);
	border-radius: 10px;
	margin: 0 auto;
	margin-top: 30px;
	padding: 20px;
	.header {
		display: flex;
		justify-content: space-between;
		font-size: 18px;
		font-family: SourceHanSansCN-Medium, SourceHanSansCN;
		font-weight: 500;
		color: #2C2C2C;
		margin-bottom: 25px;
		.key_icon {
		  width: 16px;
			height: 16px;
			background: url('../../assets/systemSetup/setup_icon.png');
			background-size: 100%;
			margin-right: 10px;
		}
		.search_input {
			width: 300px;
		}
		.search_btn {
			margin-left: 80px;
		}
	}

  .dashboard {
    padding-left: 26px;

    .radioGroup {
      margin-top: 15px;
      &Item {
        height: 16px;
        margin-bottom: 19px;
      }
      &Item:last-child {
        margin-bottom: 0;
      }
    }
    .saveBtn {
      width: 100px;
    }

    .clearLinuxButton {
      background: #FFFFFF;
      border-color: #F96A00;
      color: #F96A00;
    }
    .clearLinuxTip {
      @include FifthFont(#939393,400);
    }

    ::v-deep .el-form-item__label {
      text-align: left;
    }
  }
}

.flex {
	display: flex;
	align-items: center;
}

.edit_icon {
	background: url('../../assets/edit@list.png');
  @include list_icons;
}

.delete_icon{
  background: url('../../assets/delete@list.png');
  @include list_icons;
}
</style>
